﻿
var documentheight = $(document).height();
let easymde = null;

var htmlFormat = function (text) {
	text = text.replace(/<div (.*?)>/gi, " ");
	text = text.replace(/<div>/gi, " ");
	text = text.replace(/<span (.*?)>/gi, "");
	text = text.replace(/<span>/gi, "");
	text = text.replace(/<\/span>/gi, " ");
	text = text.replace(/<pre (.*?)>/gi, "");
	text = text.replace(/<pre>/gi, "");
	text = text.replace(/<\/pre>/gi, " ");
	text = text.replace(/<p> #/g, " \n#");
	text = text.replace(/<p>#/g, " \n#");
	text = text.replace(/<p>/g, "\n");
	text = text.replace(/<\/div>/gi, "\n");
	text = text.replace(/<\/p>/g, "\n");
	text = text.replace(/<br \/>/g, "\n");
	text = text.replace(/<br\/>/g, "\n");
	text = text.replace(/<br>/g, "\n");
	text = text.replace(/<b>/g, "");
	text = text.replace(/<\/b>/g, "");
	text = text.replace(/&nbsp;/g, " ");
	text = text.replace(/&gt;/g, ">");
	text = text.replace(/&lt;/g, "<");
	text = text.replace(/\n\n/g, "\n");
	return text;
}

var parameter = {
	layeditindex: 0
};

var request = {

	// 获取分类信息
	gettype: function (id) {
		return ('.v1/Information/InformationType/' + id).ApiItoolService();
	},

	// 新增分类信息
	insertType: '.v1/Information/InformationType',
	
	// 删除信息
	deleteInfo: function (id) {
		return ('.v1/Information/' + id);
	},

	// 删除分类信息
	deleteType: function (id) {
		return ('.v1/Information/InformationType/' + id);
	},

	// 属性操作
	execAttribute: '.v1/Information/InformationType/.attr'
};


var Action = {

	// 清除缓存
	ClearRedisCache: function () {
		$.get("/share/ClearRedisCache/" + window.app.projectId);
	},

	GetDetailsDataByProject: function () {
		var loadIndex = layer.load();
		// 35
		$.get("/share/GetDetailsData/" + window.app.projectId, function (data) {
			window.app.catalog = data;
			window.app.expandedKeys = data.length > 0 ? [data[0].id] : [];
			layer.close(loadIndex);
		})
	},

	layedit: function (layedit) {

		if (window.app.article.value) {
			window.app.article.value = htmlFormat(window.app.article.value)
		}

		easymde.init({
			element: document.getElementById("detail"), //文本域ID
			autosave: {
				enabled: false, //开启自动保存
				uniqueId: "MyUniqueID", //唯一ID值，通过唯一ID值进行保存编写记录
				delay: 1000, //多少毫秒保存一次
			},
			initialValue: window.app.article.value || "> Starting...",

			promptURLs: true, // 如果设置为true，则会显示一个JS警报窗口，要求提供链接或图像URL。默认为false。
			renderingConfig: {
				codeSyntaxHighlighting: true, //开启代码高亮
			},
			placeholder: "|",
			//status: ["autosave", "lines", "words","cursor"], //设置为false 则禁用状态栏 默认为true 开启所有
			toolbar: [
				//展示所有工具栏,如果不指定有默认的选项。
				"bold", //黑体
				"italic", //斜体
				"strikethrough", //删除线
				"heading", //标题
				//"heading-smaller", //缩小标题
				//"heading-bigger", // 增大标题
				//"heading-1", //小标题
				//"heading-2", //中标题
				//"heading-3", //大标题
				"|", //分割线
				"code", // 代码块
				"quote", //引用
				"unordered-list", // 无序列表
				"ordered-list", // 有序列表
				"clean-block", // 清除块样式
				"|", //分割线
				"link", //添加超链接
				"image", //添加图片
				"table", //添加表格
				"horizontal-rule", // 水平线
				"|",
				"side-by-side", //分屏预览
				"fullscreen", //全屏
				"|", //分割线
				"undo", //清空
				"redo", // 重做
				"|", //分割线
				"preview", //全屏预览

				//"guide", // 说明
			],
			upload: {
				url: location.host.indexOf("janjanle.com") > -1 ? "http://gateway.janjanle.com/storage" : "https://gateway.itool.store/storage"
			}
		});

		$(".CodeMirror-scroll").css("height", documentheight - 300 + 'px');

		var uploadFile = function (simplemde, fileName, formData, isImage) {
			return $.ajax({
				url: location.host.indexOf("janjanle.com") > -1 ? "http://gateway.janjanle.com/storage" : "https://gateway.itool.store/storage",
				type: 'post',
				data: formData,
				contentType: false,
				processData: false,
				success: function (res) {
					if (res.id) {
						let url = (isImage ? '!' : '') + '[' + (isImage ? '' : 'download ') + res.name + '](' + (location.host.indexOf("janjanle.com") > -1 ? "http://gateway.janjanle.com" : "https://gateway.itool.store") + '/storage/' + res.id + (isImage ? '/view)' : ')');
						let content = simplemde.getValue()
						simplemde.setValue(content + url + '\n')
					} else {
						layer.msg("文件上传失败", {
							icon: 5,
						});
					}
				},
				error: function () {
					layer.msg("上传 [" + fileName + "] 发生错误, 不支持文件夹上传");
				}
			})
		}

		var onCheckUploadEvent = function (isClipboard, e) {
			var isSupport = false;

			if (isClipboard) {
				isSupport = e.clipboardData && e.clipboardData.items;
			} else {
				isSupport = e.dataTransfer && e.dataTransfer.files;
			}

			if (!isSupport) {
				return
			}

			let dataList = isClipboard ? e.clipboardData.items : e.dataTransfer.files;

			try {

				var fileInfos = []

				for (var i = 0; i < dataList.length; i++) {
					var file = isClipboard ? dataList[i].getAsFile() : dataList[i];
					if (file) {
						fileInfos.push(file)
					}
				}

				if (fileInfos.length) {
					e.preventDefault()
					layer.confirm(fileInfos.map(a => a.name).join('<br />'),
						{
							btn: ['确认', '取消'], //按钮
							title: "上传粘贴板文件"
						}, function (index) {
							layer.close(index);

							if (fileInfos.length > 2) {
								layer.msg("每次最多上传2个文件");
								return;
							}

							if (window.app.article.id === 0) {
								return layer.msg("请选择需要编辑的文档");
							}

							index = layer.load(1);

							var uploadFileRequestList = []

							try {
								for (var i = 0; i < fileInfos.length; i++) {
									var fileInfo = fileInfos[i];
									//console.log(fileInfo)
									let formData = new FormData()
									formData.append('file', fileInfo, fileInfo.name)

									// image max 512 kb
									// other max 2MB
									var maxSize = fileInfo.type.indexOf('image') !== -1 ? 512 : 2048;

									if ((fileInfo.size / 1024) <= maxSize) {
										var request = uploadFile(easymde.codemirror, fileInfo.name, formData, maxSize == 512)
										uploadFileRequestList.push(request);
									} else {
										if (maxSize == 512) {
											layer.msg("上传图片大小不可超过 512Kb,建议使用截图工具剪贴后上传");
										} else {
											layer.msg("上传文件大小不可超过 2Mb");
										}
									}
								}
								Promise.all(uploadFileRequestList).then(res => {
									layer.close(index);
								}).catch(error => {
									layer.close(index);
								});
							} catch (e) {
								layer.close(index);
								layer.msg("上传发生错误，请重试");
							}
						}, function () {
							// 取消
						});
				}

			} catch (e) {
				// 弹窗说明，只能粘贴图片
			}
		}

		easymde.codemirror.on('paste', (editor, e) => onCheckUploadEvent(true, e))
		easymde.codemirror.on('drop', (editor, e) => onCheckUploadEvent(false, e))

	},

	regBtn: function () {

		$("[lay-filter='submit']").click(function () {

			window.app.article.title = $("#title").val();
			//window.app.article.value = layui.layedit.getContent(parameter.layeditindex);
			window.app.article.value = easymde.value();

			if (window.app.article.id === 0) {
				return layer.msg("请选择需要编辑的文档");
			}

			var submitparamter = {
				id: window.app.article.id,
				title: window.app.article.title,
				content: window.app.article.value,
				extend: JSON.stringify({ "projectId": window.app.projectId }),
				sort: (window.app.article.sort - 0) || 0
			};

			$.apiput(".v1/Information", submitparamter, function (e) {
				layer.msg('修改成功');
				window.app.saveArticleEvent();
				Action.ClearRedisCache();
			});

		});
	}

};

window.onload = function () {
	Action.layedit(layui.layedit);
	Action.regBtn();
}

window.app = new Vue({

	el: "#content",
	data: {
		projectId: 0,

		article: {
			id: 0,
			title: "",
			value: "",
			sort: 0
		},

		expandedKeys: [],

		projects: window.projectList,
		catalog: []
	},
	

	methods: {

		// 添加项目
		addproject: function () {

			var that = this;

			layer.prompt({ title: '添加项目', offset: ['260px', '260px'] }, function (title, index, elem) {

				if (title) {
					$.apipost(request.insertType, {
						"title": title,
						"upKey": window.typeKey,
						"topKey": 29
					}, function (e) {

						layer.msg("添加成功");

						that.projects.push({
							Id: e,
							Title: title,
							Class: ""
						});


					});
				} else {
					layer.msg('项目名称不能未空');
				}


				layer.close(index);
			});

		},

		// 选择项目
		TapProjectItem: function (item) {

			if (this.projectId === item.Id) {
				return;
			}

			// 激活处理
			for (var i = 0; i < this.projects.length; i++) {
				if (this.projects[i].Class === "active") {
					this.projects[i].Class = "";
				}
			}

			item.Class = "active";

			// 处理当前项目ID
			this.projectId = item.Id;

			// 获取当前项目菜单
			Action.GetDetailsDataByProject();
		},

		// 是否包含子类
		IsHaveChildNodes(node) {
			return node.childNodes.length > 0 ? false : true;
		},

		// 删除一个目录
		remove(node, data) {

			layer.confirm('确认要删除该' + ((data.type === "Doc") ? "文档" : "目录") +'？', {
				btn: ['确认', '取消'] //按钮
			}, function (index1111) {

					var rrrr = false;

					if (data.type === "Doc") {
						rrrr = request.deleteInfo(data.id);
					} else if (data.type === "Folder") {
						rrrr = request.deleteType(data.id);
					}

					if (!rrrr) {
						return layer.msg("未知操作");
					}

					$.apidelete(rrrr, function (e) {
						const parent = node.parent;
						const children = parent.data.children || parent.data;
						const index = children.findIndex(d => d.id === data.id);
						children.splice(index, 1);

						Action.ClearRedisCache();
						layer.close(index1111);
					});

				

			}, function () {
				// 取消
			});

			

			
		},

		// 编辑指定项目信息
		EditProjectItem: function (item) {

			console.log(item)

			var EditRemark = function (key, value, index) {

				if (key) {
					$.apiput(request.execAttribute, {
						id: key,
						content: JSON.stringify({
							content: value
						})
					}, function () {
						layer.msg("修改成功");
						item.Remark = value;
					});
				} else {
					$.apipost(request.execAttribute, {
						id: key,
						type: 4,
						typeKey: item.Id,
						content: JSON.stringify({
							content: value
						})
					}, function (key) {
						layer.msg("添加成功");
						item.Remark = value;
						item.RemarkKey = key;
					});

				}

				layer.close(index);

			}

			layer.open({
				id: 1,
				type: 1,
				title: '修改项目信息',
				area: ['430px', 'auto'],
				content: ' <div class="row" style="width: 400px;  margin-left:7px; margin-top:10px;">'
					+ '<div class="col-sm-12">'
					+ '<div class="input-group">'
					+ '<span class="input-group-addon" style="width: 60px;line-height: 28px;"> 名 称 :</span>'
					+ '<input id="aTitle" type="text" class="form-control" value="' + item.Title + '" placeholder="请输入修改名称" />'
					+ '</div>'
					+ '</div>'
					+ '<div class="col-sm-12" style="margin-top: 10px">'
					+ '<div class="input-group">'
					+ '<span class="input-group-addon" style="width: 60px;line-height: 28px;"> 描 述 :</span>'
					+ '<textarea class="layui-layer-input" style="height: 100px;border: 1px solid #e6e6e6;color: #333;width: 320px;padding: 10px;" id="aRemark">' + item.Remark + '</textarea>'
					+ '</div>'
					+ '</div>'
					+ '</div>'
				,
				btn: ['保存', '取消'],
				btn1: function (index, layero) {
					var aTitle = $("#aTitle").val();
					var aRemark = $("#aRemark").val();

					if (item.Title !== aTitle) {
						$.apiput(request.insertType, {
							id: item.Id,
							title: aTitle
						}, function (row) {

							item.Title = aTitle;
							Action.ClearRedisCache();

							if (item.Remark !== aRemark) {
								EditRemark(item.RemarkKey - 0, aRemark, index);
							} else {
								layer.close(index);
							}

						});
					} else if (item.Remark !== aRemark) {
						EditRemark(item.RemarkKey - 0, aRemark, index);
					}
				},
				btn2: function (index, layero) {
					layer.close(index);
				}

			});

		},

		// 选择目录
		selectCatalog: function (node) {

			var that = this
			

			if (node.data.type === "Doc") {
				this.article.id = node.data.id;
				this.article.title = node.data.label;
				this.article.value = node.data.content;
				$("#layedit").val(node.data.content || " ")
				this.article.sort = (node.data.sort - 0) || 0;
				setTimeout(function () {
					Action.layedit(layui.layedit);
				}, 100);
			} else {

				layer.open({
					id: 1,
					type: 1,
					title: '修改分类信息',
					area: ['430px', 'auto'],

					content: ' <div class="row" style="width: 400px;  margin-left:7px; margin-top:10px;">'
						+ '<div class="col-sm-12">'
						+ '<div class="input-group">'
						+ '<span class="input-group-addon" style="width: 60px;line-height: 28px;"> 排 序 :</span>'
						+ '<input id="aSort" type="text" class="form-control" value="' + node.data.sort + '" placeholder="按从小到大排序，忽略0">'
						+ '</div>'
						+ '</div>'
						+ '<div class="col-sm-12" style="margin-top: 10px">'
						+ '<div class="input-group">'
						+ '<span class="input-group-addon" style="width: 60px;line-height: 28px;"> 名 称 :</span>'
						+ '<input id="aTypeTitle" type="text" value="' + node.data.label +'" class="form-control" placeholder="分类名称">'
						+ '</div>'
						+ '</div>'
						+ '</div>'
					,
					btn: ['保存', '取消'],
					btn1: function (index, layero) {
						var sort = $("#aSort").val() - 0;
						var title = $("#aTypeTitle").val();


						if (isNaN(sort)) {
							layer.msg('排序字段数据只能为数字');
							return;
						}

						that.article.id = node.data.id;
						that.article.sort = (sort - 0) || 0;
						that.article.title = title;

						$.apiput(request.insertType, {
							id: node.data.id - 0,
							title: title,
							sort: sort - 0
						}, function (row) {
							node.data.label = title;
							node.data.sort = (sort - 0) || 0;
							Action.ClearRedisCache();
							setTimeout(window.app.saveArticleEvent, 100)
							layer.close(index);
						});

					},
					btn2: function (index, layero) {
						layer.close(index);
					}

				});
			}

			console.log(node)

		},

		// 添加文章
		appendDoc: function (data) {

			var that = this;

			console.log(that.catalog)

			layer.prompt({ title: '添加文档', offset: ['260px', '580px'] }, function (title, index, elem) {

				if (title) {

					var type = (data || {}).id || that.projectId;

					$.apipost(".v1/Information", {
						typeKey: type,
						title: title,
						extend: JSON.stringify({ "projectId": that.projectId }),
						content: ""
					}, function (key) {

							console.log(key)

							if (data) {
								const newChild = { id: key, label: title, type: 'Doc' };
								if (!data.children) {
									that.$set(data, 'children', []);
								}
								data.children.push(newChild);
							} else {
								that.catalog.push({
									id: key,
									label: title,
									type: 'Doc',
									content: ""
								});
							}

							Action.ClearRedisCache();

					});
					

				} else {
					layer.msg('文档名称不能未空');
				}


				layer.close(index);
			});

		},

		// 添加目录
		appendFolder: function (data) {

			var that = this;

			layer.prompt({ title: '添加目录', offset: ['260px', '580px'] }, function (title, index, elem) {

				if (title) {

					var type = (data || {}).id || that.projectId;

					$.apipost(request.insertType, {
						"title": title,
						"upKey": type - 0,
						"topKey": 29,
						"sort": 0
					}, function (key) {

						if (data) {
							const newChild = { id: key, label: title, type: 'Folder', children: [] };
							if (!data.children) {
								that.$set(data, 'children', []);
							}
							data.children.push(newChild);
						} else {
							that.catalog.push({
								id: key,
								label: title,
								type: 'Folder',
								children: []
							});
						}

						Action.ClearRedisCache();

					});

				} else {
					layer.msg('目录名称不能未空');
				}


				layer.close(index);
			});

			

		},

		// 保存文章触发事件
		saveArticleEvent: function ()
		{
			var that = this;

			var orderby = function (data)
			{
				return data.sort(function (a, b) {
					return a.sort - b.sort
				});
			}

			var lookupChildren = function (data)
			{
				for (var i = 0; i < data.children.length; i++) {
					var item = data.children[i];
					if (item.id === that.article.id) {
						item.label = that.article.title;
						item.content = that.article.value;
						item.sort = (that.article.sort - 0) || 0;

						var s = orderby(data.children);
						data.children = [];
						setTimeout(function () {
							data.children = s;
						}, 100);
						return;
					} else if (item.children.length) {
						lookupChildren(item);
					}
				}
			}

			for (var i = 0; i < this.catalog.length; i++) {
				var item = this.catalog[i];

				if (item.id === this.article.id) {
					item.label = this.article.title;
					item.content = this.article.value;
					item.sort = (this.article.sort - 0) || 0;


					console.log(item)

					var s = orderby(this.catalog);
					this.catalog = [];
					setTimeout(function () {
						that.catalog = s;
					}, 100);

					return;
				} else if (item.children.length) {
					lookupChildren(item);
				}
			}
		}
	}

});


// markdown edit
layui.config({
	base: "/lib/easymde-layui/mods/",
}).extend({
	easymde: 'easymde/easymde',
});

//JavaScript代码区域
layui.use(["easymde"], function () {
	const $ = layui.$;
	easymde = layui.easymde;
});